﻿using EFCore.BulkExtensions;
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using iWare.Wms.Core;
using iWare.Wms.Core.Entity.Receiving;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System.Linq.Dynamic.Core;
using Yitter.IdGenerator;

namespace iWare.Wms.Application
{
    /// <summary>
    /// 采购订单服务
    /// </summary>
    [Route("api/PurchaseOrder")]
    [ApiDescriptionSettings("供应商模块", Name = "PurchaseOrder", Order = 110)]

    public class PurchaseOrderService : IDynamicApiController, ITransient
    {
        private readonly ILogger<PurchaseOrderService> _logger;
        private readonly ISqlRepository<ERPDbContextLocator> _erpRep;
        private readonly IRepository<SupplierInfo, MasterDbContextLocator> _supplierInfoRep;
        private readonly IRepository<WareMaterial, MasterDbContextLocator> _wareMaterialRep;
        private readonly IRepository<PurchaseOrder, MasterDbContextLocator> _purchaseOrderRep;
        private readonly IRepository<GoodsDelivery, MasterDbContextLocator> _goodsDeliveryRep;
        private readonly IRepository<GoodsDeliveryDetails, MasterDbContextLocator> _goodsDeliveryDetailsRep;
        private readonly IRepository<GoodsDeliveryAppointment, MasterDbContextLocator> _goodsDeliveryAppointmentRep;
        private readonly IRepository<GoodsDeliveryTagPrint, MasterDbContextLocator> _goodsDeliveryTagPrintRep;
        private readonly IRepository<PurchaseOrderVsGoodsDelivery, MasterDbContextLocator> _purchaseOrderVsGoodsDeliveryRep;
        private readonly IRepository<SupplierExamineFlower, MasterDbContextLocator> _supplierExamineFlowerRep;
        private readonly IRepository<V_PurchaseOrder, MasterDbContextLocator> _v_purchaseOrderRep;

        #region 默认
        /// <summary>
        /// 
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="erpRep"></param>
        /// <param name="supplierInfoRep"></param>
        /// <param name="wareMaterialRep"></param>
        /// <param name="purchaseOrderRep"></param>
        /// <param name="goodsDeliveryRep"></param>
        /// <param name="goodsDeliveryDetailsRep"></param>
        /// <param name="goodsDeliveryAppointmentRep"></param>
        /// <param name="goodsDeliveryTagPrintRep"></param>
        /// <param name="purchaseOrderVsGoodsDeliveryRep"></param>
        /// <param name="supplierExamineFlowerRep"></param>
        /// <param name="v_purchaseOrderRep"></param>
        public PurchaseOrderService(
            ILogger<PurchaseOrderService> logger,
            ISqlRepository<ERPDbContextLocator> erpRep,
            IRepository<SupplierInfo, MasterDbContextLocator> supplierInfoRep,
            IRepository<WareMaterial, MasterDbContextLocator> wareMaterialRep,
            IRepository<PurchaseOrder, MasterDbContextLocator> purchaseOrderRep,
            IRepository<GoodsDelivery, MasterDbContextLocator> goodsDeliveryRep,
            IRepository<GoodsDeliveryDetails, MasterDbContextLocator> goodsDeliveryDetailsRep,
            IRepository<GoodsDeliveryAppointment, MasterDbContextLocator> goodsDeliveryAppointmentRep,
            IRepository<GoodsDeliveryTagPrint, MasterDbContextLocator> goodsDeliveryTagPrintRep,
            IRepository<PurchaseOrderVsGoodsDelivery, MasterDbContextLocator> purchaseOrderVsGoodsDeliveryRep,
            IRepository<SupplierExamineFlower, MasterDbContextLocator> supplierExamineFlowerRep,
            IRepository<V_PurchaseOrder, MasterDbContextLocator> v_purchaseOrderRep
        )
        {
            _logger = logger;
            _erpRep = erpRep;
            _supplierInfoRep = supplierInfoRep;
            _wareMaterialRep = wareMaterialRep;
            _purchaseOrderRep = purchaseOrderRep;
            _goodsDeliveryRep = goodsDeliveryRep;
            _goodsDeliveryDetailsRep = goodsDeliveryDetailsRep;
            _goodsDeliveryAppointmentRep = goodsDeliveryAppointmentRep;
            _goodsDeliveryTagPrintRep = goodsDeliveryTagPrintRep;
            _purchaseOrderVsGoodsDeliveryRep = purchaseOrderVsGoodsDeliveryRep;
            _supplierExamineFlowerRep = supplierExamineFlowerRep;
            _v_purchaseOrderRep = v_purchaseOrderRep;
        }
        #endregion

        /// <summary>
        /// 分页查询供应商采购订单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("Page")]
        public async Task<PageResult<V_PurchaseOrder>> Page([FromQuery] PurchaseOrderSearch input)
        {
            var account = CurrentUserInfo.Account;

            var purchaseOrders = await _v_purchaseOrderRep.DetachedEntities
                .Where(u => u.SupplierInfoCode == account)
                .Where(u => u.Status != PurchaseStatusEnum.Delete)
                .Where(input.IsJiaJiJian != null && input.IsJiaJiJian != YesOrNot.All, u => u.IsJiaJiJian == input.IsJiaJiJian)
                .Where(input.Status != null && input.Status != PurchaseStatusEnum.All, u => u.Status == input.Status)
                .Where(!string.IsNullOrEmpty(input.PurchaseNo), u => EF.Functions.Like(u.PurchaseNo, $"%{input.PurchaseNo.Trim()}%"))
                .Where(!string.IsNullOrEmpty(input.ProjectCode), u => EF.Functions.Like(u.ProjectCode, $"%{input.ProjectCode.Trim()}%"))
                .Where(!string.IsNullOrEmpty(input.SearchBeginTime), u => u.CreatedTime >= DateTime.Parse(input.SearchBeginTime.Trim()) &&
                 u.CreatedTime <= DateTime.Parse(input.SearchEndTime.Trim()))
                .OrderBy(u => u.Status)
                .ThenByDescending(u => u.UpdatedTime)
                .ProjectToType<V_PurchaseOrder>()
                .ToADPagedListAsync(input.PageNo, input.PageSize);

            //获取送货单数量
            foreach (var item in purchaseOrders.Rows)
            {
                var vsList = await _purchaseOrderVsGoodsDeliveryRep.DetachedEntities
                    .Where(p => p.PurchaseOrderId == item.Id).Select(p => p.GoodsDeliveryId).ToListAsync();
                item.DeliveryQuantityTotal = await _goodsDeliveryRep.DetachedEntities
                    .Where(p => vsList.Contains(p.Id)).SumAsync(p => p.DeliveryQuantityTotal);
                item.OutQuantityTotal = item.PurchaseNumber - item.DeliveryQuantityTotal;
                item.PurchaseNo = item.IsJiaJiJian == YesOrNot.Y ? "" : item.PurchaseNo;
            }

            return purchaseOrders;
        }

        /// <summary>
        /// 采购单头-LES采购主表 数据同步使用
        /// </summary>
        [HttpGet("GetPurchase")]
        public async Task GetPurchase()
        {
            var whereTime = DateTime.Now.AddMonths(-1).ToString("yyyyMMdd");
            var purtcOutputList = await _erpRep
                .SqlQueryAsync<PURTCOutput>
                (@"select TC001, --采购单别
	                          TC002, --采购单号
	                          TC003, --采购日期
	                          TC004, --供应商
	                          TC009, --备注
	                          TC011, --采购人员
	                          TC023, --数量合计
	                          TC047, --项目编号
	                          UDF01, --收货地址
	                          TC030   --签核状态码  0.待处理、S.传送中、1.签核中、2.退件、3.已核准、4.撤销审核中、5.作废中、6.取消作废中、N.不运行电子签核
                       from PURTC where TCD01 = 'N' and TC030 = '3' and TC023 > 0 and TC003>'" + whereTime + "'  order by TC003 desc");

            //循环判断LES系统中是否包含该采购信息以及状态变化
            List<PurchaseOrder> PurchaseOrderList = new List<PurchaseOrder>();
            foreach (var item in purtcOutputList)
            {
                var isExists = await _purchaseOrderRep
                    .AnyAsync(u => u.PurchaseNo == item.TC002
                     && u.PurchaseType == item.TC001 && u.Status != PurchaseStatusEnum.Delete);
                //不存在执行新增操作
                if (!isExists)
                {
                    var addItem = new PurchaseOrder()
                    {
                        PurchaseType = item.TC001.Trim(),
                        PurchaseNo = item.TC002.Trim(),
                        PurchaseDate = DateTime.ParseExact(item.TC003.ToString().Trim(),
                        "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture),
                        SupplierInfoCode = item.TC004.Trim(),
                        Remark = item.TC009 == null ? "" : item.TC009.Trim(),
                        PurchaserUserId = item.TC011.Trim(),
                        PurchaseNumber = item.TC023,
                        ProjectCode = item.TC047.Trim(),
                        Address = item.UDF01.Trim(),
                        Status = PurchaseStatusEnum.NotProgress,
                        CreatedTime = DateTimeOffset.Now
                    };
                    PurchaseOrderList.Add(addItem);
                }
            }

            //批量新增 通过 Nuget 安装 EFCore.BulkExtensions 包即可。
            _purchaseOrderRep.Context.BulkInsert(PurchaseOrderList);
        }

        /// <summary>
        /// 供应商创建送货单的二次判断
        /// </summary>
        /// <returns></returns>
        [HttpPost("CheckPurchase")]
        public async Task<PURTCResult> CheckPurchase(PURTCSearch PURTCSearch)
        {
            if (string.IsNullOrEmpty(PURTCSearch.TC002)) throw Oops.Oh(ErrorCode.D1011);

            var purtcOutputList = await _erpRep
                .SqlQueryAsync<PURTCOutput>
                (@"select TC001, --采购单别
	                      TC002, --采购单号
	                      TC003, --采购日期
	                      TC004, --供应商
	                      TC009, --备注
	                      TC011, --采购人员
	                      TC023, --数量合计
	                      TC047, --项目编号
	                      UDF01, --收货地址
	                      TC030  --签核状态码  0.待处理、S.传送中、1.签核中、2.退件、3.已核准、4.撤销审核中、5.作废中、6.取消作废中、N.不运行电子签核
                   from PURTC where TCD01 = 'N' and TC030 = '3' and TC023 > 0  
                   and TC002='" + PURTCSearch.TC002 + "' and TC001='" + PURTCSearch.TC001 + "'");
            if (purtcOutputList.Count > 0)
            {
                return new PURTCResult
                {
                    IsCreate = true
                };
            }
            else
            {
                //修改LES系统单据的状态
                var model = await _purchaseOrderRep
                    .SingleOrDefaultAsync(u => u.PurchaseNo == PURTCSearch.TC002
                     && u.PurchaseType == PURTCSearch.TC001 && u.Status != PurchaseStatusEnum.Delete, true);
                if (model != null)
                {
                    model.Status = PurchaseStatusEnum.Delete;
                }
                return new PURTCResult
                {
                    IsCreate = false,
                    Message = "采购单被撤销或不存在!"
                };
            }
        }

        /// <summary>
        /// 获取创建送货单列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("CreateGoodsDeliveryList")]
        public async Task<PageResult<PurtdDetailsOutput>> CreateGoodsDeliveryList([FromQuery] PurchaseOrderDetailsInput input)
        {
            //创建需要映射的送货单明细集合
            List<GoodsDeliveryDetailsOutput> purchaseOrderDetailsList = new();

            //获取采购单下排除当前送货单号下所有的送货单明细集合
            var othergoodsDeliveryIdItem = await _purchaseOrderVsGoodsDeliveryRep.DetachedEntities
                .Where(p => p.PurchaseOrderId == input.PurchaseID)
                .Select(n => n.GoodsDeliveryId).ToListAsync();

            var currGoodDeliveryDetailList = await _goodsDeliveryDetailsRep.DetachedEntities
                .Where(p => othergoodsDeliveryIdItem.Contains(p.GoodsDelivery.Id)).ToListAsync();

            //根据ERP查询
            var purchaseModel = await _purchaseOrderRep.SingleOrDefaultAsync(p => p.Id == input.PurchaseID);
            var pURTCSearch = new PURTCSearch()
            {
                TC002 = purchaseModel.PurchaseNo,
                TC001 = purchaseModel.PurchaseType
            };

            var pURTDOutputsList = await RedPURTD(input, pURTCSearch.TC002, pURTCSearch.TC001);
            if (pURTDOutputsList.TotalRows == 0 && string.IsNullOrEmpty(input.PurchaseCode) && string.IsNullOrEmpty(input.PurchaseName)) throw Oops.Oh("该采购单下无采购明细!");

            foreach (var item in pURTDOutputsList.Rows)
            {
                //物料送货数量达到采购数量,不显示出来
                var sumcount = currGoodDeliveryDetailList
                    .Where(u => u.Code == item.Code.Trim() && u.Name == item.Name.Trim() && u.SpecificationModel == item.SpecificationModel.Trim())
                    .Select(t => t.DeliveryQuantity).Sum();
                //if (sumcount >= item.TD008) continue;
                if (sumcount >= item.PurchaseNumber) item.IsCheck = true; //不显示出来只能做到不勾选

                // 送货单数量
                var deliveryQuantity = item.PurchaseNumber - sumcount;

                //获取物料的检验方式
                var wareMateriaModel = await SelectMaterial(item.Code, item.SpecificationModel);

                //是否结束
                string isEnd = string.Empty;
                if (item.IsEnd.Trim() == "N") isEnd = "未结束";
                else if (item.IsEnd.Trim() == "Y") isEnd = "结束";
                else isEnd = "指定结束";

                // 品牌名称查询
                var wareMaterial = await _wareMaterialRep.FirstOrDefaultAsync(z => z.Code == item.Code.Trim()
                    && z.Name == item.Name.Trim() && z.SpecificationModel == item.SpecificationModel.Trim());

                item.PurchaseType = item.PurchaseType.Trim();
                item.PurchaseNo = item.PurchaseNo.Trim();
                item.ProjectCode = item.ProjectCode.Trim();
                item.Code = item.Code.Trim();
                item.Name = item.Name.Trim();
                item.XuHao = item.XuHao.PadLeft(4, '0');
                item.SpecificationModel = item.SpecificationModel.Trim();
                item.Unit = item.Unit.Trim();
                item.InspectionMethod = wareMateriaModel != null ? wareMateriaModel.InspectionMethod : InspectionMethodEnum.mianjian;
                item.BrandName = wareMaterial == null || wareMaterial.BrandName == "无" ? "" : wareMaterial.BrandName;
                item.DeliveryQuantity = deliveryQuantity;
                item.OutdeliveryQuantity = sumcount;
                item.NotPurchaseNumber = item.PurchaseNumber - (sumcount + deliveryQuantity);
            };

            return pURTDOutputsList;
        }

        /// <summary>
        /// 新增送货单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("AddGoodsDelivery")]
        //[UnitOfWork]
        public async Task AddGoodsDelivery(AddGoodsDeliveryInput input)
        {
            //查询采购单信息
            var purchaseModel = await _v_purchaseOrderRep.FirstOrDefaultAsync(p => p.Id == input.PurchaseID);

            //新增送货主表
            var goodsDeliveryModel = new GoodsDelivery()
            {
                DeliveryNo = YitIdHelper.NextId().ToString(),
                SuppCode = purchaseModel.SupplierInfoCode.Trim(),
                SuppName = purchaseModel.SupplierInfoName,
                SuppPhone = purchaseModel.SupplierTel,
                SuppAddress = purchaseModel.SuppAddress,
                ProjectCode = purchaseModel.ProjectCode,
                ReceName = "伟本智能（上海）股份有限公司",
                ReceAddress = purchaseModel.Address,
                RecePhone = "021-57709082-8194或9183",
                ReceUser = purchaseModel.PurchaserUserName,
                PurchaseNo = purchaseModel.PurchaseNo,
                DeliveryType = purchaseModel.PurchaseType,
                DeliveryQuantityTotal = input.GoodsDeliveryDetailsInputList.Sum(t => t.DeliveryQuantity)
            };
            await _goodsDeliveryRep.InsertAsync(goodsDeliveryModel, true);

            _logger.LogInformation($@"[PurchaseOrderService-AddGoodsDelivery]送货单号:{goodsDeliveryModel.DeliveryNo},创建送货单主表:{goodsDeliveryModel.ToJson()}");
            _logger.LogInformation($"[PurchaseOrderService-AddGoodsDelivery]前端接收-送货单号:{goodsDeliveryModel.DeliveryNo},创建送货单明细总数:{input.GoodsDeliveryDetailsInputList.Count()};详情:" + input.GoodsDeliveryDetailsInputList.ToJson());

            //新增采购送货关系表
            var vsitem = new PurchaseOrderVsGoodsDelivery()
            {
                PurchaseOrderId = input.PurchaseID,
                GoodsDeliveryId = goodsDeliveryModel.Id
            };
            await _purchaseOrderVsGoodsDeliveryRep.InsertAsync(vsitem);

            //更新采购单据状态为“进行中”
            var purchaseOrderModel = await _purchaseOrderRep.FirstOrDefaultAsync(p => p.Id == purchaseModel.Id, true);
            purchaseOrderModel.Status = PurchaseStatusEnum.Progress;
            await _purchaseOrderRep.UpdateAsync(purchaseOrderModel);
            _logger.LogInformation($"[PurchaseOrderService-AddGoodsDelivery]采购单号:{purchaseModel.PurchaseNo},更新采购单状态为进行中:{PurchaseStatusEnum.Progress}");

            //创建一条提交记录
            var supplierExaminerFlowerModel = new SupplierExamineFlower()
            {
                Status = AuditStatusEnum.yuyuezhong, //预约中
                DeliveryID = goodsDeliveryModel.Id,
                Remarks = "预约中"
            };
            await _supplierExamineFlowerRep.InsertAsync(supplierExaminerFlowerModel);

            //批量新增送货详情信息
            List<GoodsDeliveryDetails> goodsDeliveryDetailList = new();
            //批量新增送货标签打印记录信息
            List<GoodsDeliveryTagPrint> goodsDeliveryTagPrintList = new List<GoodsDeliveryTagPrint>();

            foreach (var item in input.GoodsDeliveryDetailsInputList)
            {
                item.GoodsDeliveryId = goodsDeliveryModel.Id;
                var goodsDeliveryDetails = item.Adapt<GoodsDeliveryDetails>();
                goodsDeliveryDetails.Id = YitIdHelper.NextId();
                goodsDeliveryDetails.GoodsDeliveryId = goodsDeliveryModel.Id;
                goodsDeliveryDetails.SupplierInfoCode = goodsDeliveryModel.SuppCode.Trim();
                goodsDeliveryDetails.CreatedUserId = CurrentUserInfo.UserId;
                goodsDeliveryDetails.CreatedUserName = CurrentUserInfo.Name;
                goodsDeliveryDetails.CreatedTime = DateTimeOffset.Now;
                goodsDeliveryDetails.BrandName = await _wareMaterialRep.Where(z => z.Code == item.Code && z.SpecificationModel == item.SpecificationModel)
                    .Select(z => z.BrandName).FirstOrDefaultAsync();
                goodsDeliveryDetailList.Add(goodsDeliveryDetails);

                var wareMaterialTagModel = item.Adapt<GoodsDeliveryTagPrint>();
                var goodsDeliveryTagPrintModel = item.Adapt<GoodsDeliveryTagPrint>();
                wareMaterialTagModel.GoodsDeliveryId = goodsDeliveryModel.Id;
                wareMaterialTagModel.DeliveryNo = goodsDeliveryModel.DeliveryNo;
                wareMaterialTagModel.SupplierInfoCode = goodsDeliveryModel.SuppCode.Trim();
                wareMaterialTagModel.Quantity = item.DeliveryQuantity;
                wareMaterialTagModel.BrandName = await _wareMaterialRep.Where(z => z.Code == item.Code && z.SpecificationModel == item.SpecificationModel)
                    .Select(z => z.BrandName).FirstOrDefaultAsync();
                wareMaterialTagModel.CreatedUserId = CurrentUserInfo.UserId;
                wareMaterialTagModel.CreatedUserName = CurrentUserInfo.Name;
                wareMaterialTagModel.CreatedTime = DateTimeOffset.Now;
                goodsDeliveryTagPrintList.Add(wareMaterialTagModel);
            }

            //批量新增 通过 Nuget 安装 EFCore.BulkExtensions 包即可。
            await _goodsDeliveryDetailsRep.Context.BulkInsertAsync(goodsDeliveryDetailList);
            await _goodsDeliveryTagPrintRep.Context.BulkInsertAsync(goodsDeliveryTagPrintList);

            _logger.LogInformation($"[PurchaseOrderService-AddGoodsDelivery]后端提交-送货单号:{goodsDeliveryModel.DeliveryNo},创建送货单明细总数:{goodsDeliveryDetailList.Count()};详情:" + goodsDeliveryDetailList.ToJson());
            _logger.LogInformation($"[PurchaseOrderService-AddGoodsDelivery]后端提交-送货单号:{goodsDeliveryModel.DeliveryNo},创建送货单标签打印总数:{goodsDeliveryTagPrintList.Count()};详情:" + goodsDeliveryTagPrintList.ToJson());
        }

        /// <summary>
        /// 分页查询供应商加急件
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("UrgentItemPage")]
        public async Task<PageResult<PurchaseUrgentItemOutput>> UrgentItemPage([FromQuery] PurchaseUrgentItemInput input)
        {
            var account = CurrentUserInfo.Account;

            return await _wareMaterialRep.DetachedEntities.Where(z => z.IsJiaJi == YesOrNot.Y)
                .Where(u => u.SupplerCode == account).OrderByDescending(t => t.CreatedTime)
                .ProjectToType<PurchaseUrgentItemOutput>().ToADPagedListAsync(input.PageNo, input.PageSize);
        }

        /// <summary>
        /// 新建加急件
        /// </summary>
        [HttpPost("AddUrgentItem")]
        //[UnitOfWork]
        public async Task AddUrgentItem(AddPurchaseForJiaJiJianInput input)
        {
            var supplierInfo = await _supplierInfoRep.FirstOrDefaultAsync(z => z.Code == CurrentUserInfo.Account);

            // 构建采购单信息
            PurchaseOrder purchaseModel = new PurchaseOrder()
            {
                PurchaseNo = YitIdHelper.NextId().ToString(), // 系统生成虚拟采购单号
                ProjectCode = input.ProjectCode,
                PurchaseType = "UrgentItem", //默认先写UrgentItem（加急件），后面再确认
                Address = "上海松江区文吉路555号（伟本仓库）",
                SupplierInfoCode = supplierInfo.Code,
                PurchaseNumber = input.MaterialJiaJiJians.Sum(t => t.deliveryQuantity),
                Status = PurchaseStatusEnum.Progress,
                IsJiaJiJian = YesOrNot.Y,
                PurchaseDate = DateTimeOffset.Now
            };
            await _purchaseOrderRep.InsertAsync(purchaseModel, true);

            // 构建送货单
            GoodsDelivery goodsDeliveryModel = new GoodsDelivery()
            {
                PurchaseNo = purchaseModel.PurchaseNo,
                DeliveryNo = YitIdHelper.NextId().ToString(),
                DeliveryType = purchaseModel.PurchaseType,
                Status = AuditStatusEnum.songhuozhong,
                SuppCode = supplierInfo.Code,
                SuppName = supplierInfo.Name,
                SuppPhone = supplierInfo.Tel,
                SuppAddress = supplierInfo.ContactAddress,
                ProjectCode = input.ProjectCode,
                ReceName = "伟本智能（上海）股份有限公司",
                ReceAddress = purchaseModel.Address,
                RecePhone = "021-57709082-8194或9183",
                DeliveryQuantityTotal = input.MaterialJiaJiJians.Sum(t => t.deliveryQuantity),
                IsJiaJiJian = YesOrNot.Y
            };
            await _goodsDeliveryRep.InsertAsync(goodsDeliveryModel, true);

            _logger.LogInformation($@"[PurchaseOrderService-AddUrgentItem]送货单号:{goodsDeliveryModel.DeliveryNo},创建加急件送货单主表:{goodsDeliveryModel.ToJson()}");
            _logger.LogInformation($"[PurchaseOrderService-AddUrgentItem]前端接收-送货单号:{goodsDeliveryModel.DeliveryNo},创建送货单明细总数:{input.MaterialJiaJiJians.Count()};详情:" + input.MaterialJiaJiJians.ToJson());

            //批量新增送货单明细信息
            var goodsDeliveryDetailsList = new List<GoodsDeliveryDetails>();
            //批量新增送货标签打印记录信息
            List<GoodsDeliveryTagPrint> goodsDeliveryTagPrintList = new List<GoodsDeliveryTagPrint>();
            // 遍历物料明细
            foreach (var item in input.MaterialJiaJiJians)
            {
                //获取物料的检验方式
                var wareMateriaModel = await SelectMaterial(item.Code, item.SpecificationModel);

                // 构建送货单明细
                var goodsDeliveryDetails = item.Adapt<GoodsDeliveryDetails>();
                goodsDeliveryDetails.GoodsDeliveryId = goodsDeliveryModel.Id;
                goodsDeliveryDetails.ProjectCode = input.ProjectCode.Trim();
                goodsDeliveryDetails.XuHao = item.XuHao.Trim();
                goodsDeliveryDetails.InspectionMethod = wareMateriaModel != null ? wareMateriaModel.InspectionMethod : InspectionMethodEnum.mianjian;
                goodsDeliveryDetails.SupplierInfoCode = supplierInfo.Code;
                goodsDeliveryDetails.DeliveryQuantity = item.deliveryQuantity;
                goodsDeliveryDetails.CreatedUserId = CurrentUserInfo.UserId;
                goodsDeliveryDetails.CreatedUserName = CurrentUserInfo.Name;
                goodsDeliveryDetails.CreatedTime = DateTimeOffset.Now;
                goodsDeliveryDetailsList.Add(goodsDeliveryDetails);

                // 构建送货标签明细
                var wareMaterialTagModel = item.Adapt<GoodsDeliveryTagPrint>();
                var goodsDeliveryTagPrintModel = item.Adapt<GoodsDeliveryTagPrint>();
                wareMaterialTagModel.GoodsDeliveryId = goodsDeliveryModel.Id;
                wareMaterialTagModel.DeliveryNo = goodsDeliveryModel.DeliveryNo;
                wareMaterialTagModel.ProjectCode = goodsDeliveryDetails.ProjectCode;
                wareMaterialTagModel.XuHao = item.XuHao;
                wareMaterialTagModel.InspectionMethod = wareMateriaModel != null ? wareMateriaModel.InspectionMethod : InspectionMethodEnum.mianjian;
                wareMaterialTagModel.SupplierInfoCode = goodsDeliveryModel.SuppCode.Trim();
                wareMaterialTagModel.Quantity = item.deliveryQuantity;
                wareMaterialTagModel.BrandName = await _wareMaterialRep.Where(z => z.Code == item.Code && z.SpecificationModel == item.SpecificationModel)
                .Select(z => z.BrandName).FirstOrDefaultAsync();
                wareMaterialTagModel.CreatedUserId = CurrentUserInfo.UserId;
                wareMaterialTagModel.CreatedUserName = CurrentUserInfo.Name;
                wareMaterialTagModel.CreatedTime = DateTimeOffset.Now;
                goodsDeliveryTagPrintList.Add(wareMaterialTagModel);
            }

            // 新增采购送货关系表
            var vsitem = new PurchaseOrderVsGoodsDelivery()
            {
                PurchaseOrderId = purchaseModel.Id,
                GoodsDeliveryId = goodsDeliveryModel.Id
            };
            await _purchaseOrderVsGoodsDeliveryRep.InsertAsync(vsitem);

            //创建送货预约信息
            var appointmenModel = input.Adapt<GoodsDeliveryAppointment>();
            appointmenModel.TransportCompany = "N/A";
            appointmenModel.TransportVehicle = "N/A";
            appointmenModel.DriverName = "N/A";
            appointmenModel.DriverPhone = "N/A";
            appointmenModel.DriverQualification = "N/A";
            appointmenModel.ExpressInfoNo = "N/A";
            appointmenModel.CollectDeliveryUserName = "N/A";
            appointmenModel.CollectDeliveryUserPhone = "N/A";
            appointmenModel.DeliverGoodsPlaceShip = supplierInfo.ContactAddress;
            appointmenModel.CollectDeliveryPlaceShip = "上海市松江区文吉路555号";
            appointmenModel.DeliveryID = goodsDeliveryModel.Id;
            appointmenModel.DeliveryNo = goodsDeliveryModel.DeliveryNo;
            appointmenModel.Status = AuditStatusEnum.songhuozhong; //送货中
            appointmenModel.DeliverDate = DateTimeOffset.Now; //发货日期
            appointmenModel.EstimatedDate = DateTimeOffset.Now; //预计到达日期
            await _goodsDeliveryAppointmentRep.InsertAsync(appointmenModel);

            //创建一条提交记录
            var supplierExaminerFlowerModel = new SupplierExamineFlower()
            {
                IsJiaJiJian = YesOrNot.Y,
                Status = AuditStatusEnum.songhuozhong, //送货中
                DeliveryID = goodsDeliveryModel.Id,
                Remarks = "送货中"
            };
            await _supplierExamineFlowerRep.InsertAsync(supplierExaminerFlowerModel);

            // 批量新增 通过 Nuget 安装 EFCore.BulkExtensions 包即可。
            await _goodsDeliveryDetailsRep.Context.BulkInsertAsync(goodsDeliveryDetailsList);
            await _goodsDeliveryTagPrintRep.Context.BulkInsertAsync(goodsDeliveryTagPrintList);

            _logger.LogInformation($"[PurchaseOrderService-AddUrgentItem]后端提交-送货单号:{goodsDeliveryModel.DeliveryNo},创建加急件送货单明细总数:{goodsDeliveryDetailsList.Count()};详情:" + goodsDeliveryDetailsList.ToJson());
            _logger.LogInformation($"[PurchaseOrderService-AddUrgentItem]送货单号:{goodsDeliveryModel.DeliveryNo},创建加急件送货单标签打印总数:{goodsDeliveryTagPrintList.Count()};详情:" + goodsDeliveryTagPrintList.ToJson());
        }

        /// <summary>
        /// 生成系统单号
        /// </summary>
        /// <returns></returns>
        [HttpGet("GenerateSystemNo")]
        public string GenerateSystemNo()
        {
            return YitIdHelper.NextId().ToString();
        }

        /// <summary>
        /// 采购单身-Les采购明细表
        /// </summary>
        [NonAction]
        public async Task<PageResult<PurtdDetailsOutput>> RedPURTD(PurchaseOrderDetailsInput input, string purchaseNo, string purchaseType)
        {
            if (string.IsNullOrEmpty(purchaseNo)) throw Oops.Oh(ErrorCode.D1011);
            string sql = string.Format($@"select row_number() over(order by pur.CREATE_DATE) as XuHao,
                                                 TD001 as PurchaseNo, --采购单别
	                                             TD002 as PurchaseType, --采购单号
	                                             TD004 as Code, --品号
	                                             TD005 as Name, --品名
	                                             TD006 as SpecificationModel, --规格
	                                             TD009 as Unit, --单位
	                                             --TD014, --备注
	                                             TD022 as ProjectCode, --项目编号
	                                             --UDF03, --参数
                                                 TD016 as IsEnd, --N:未结束、Y:自动结束、y:指定结束
                                                 --TD018  --审核码
						                         SUM(TD008) as PurchaseNumber
                                          from PURTD pur where TD018='Y' and TD002='{purchaseNo}' and TD001='{purchaseType}' 
                                          and TD004 like '%{input.PurchaseCode}%' and TD005 like '%{input.PurchaseName}%'
                                          group by TD001,TD002,TD004,TD005,TD006,TD009,TD016,TD022,CREATE_DATE");
            var purtdList = await _erpRep
              .SqlQueryAsync<PurtdDetailsOutput>(sql);

            int startIndex = (input.PageNo - 1) * input.PageSize + 1;
            int endIndex = startIndex + input.PageSize - 1;

            //分页
            string pageSql = @"with
                                 tb as
                                 (
                                     " + sql + @"
                                 )  select * from tb where XuHao between " + startIndex + " and " + endIndex;

            var list = await _erpRep
                .SqlQueryAsync<PurtdDetailsOutput>(pageSql);

            //throw Oops.Oh("该物料信息不存在");

            return list.ToADPagedList20230214(purtdList, input.PageNo, input.PageSize);
        }

        /// <summary>
        /// 根据条件查询物料信息
        /// </summary>
        /// <returns></returns>
        [NonAction]
        public async Task<WareMaterial> SelectMaterial(string code, string specificationModel)
        {
            var materialList = await _erpRep
                .SqlQueryAsync<MaterialErpInput>
                 (@"select MB001, --品号
	                       MB002, --品名
	                       MB003, --规格
	                       MB004, --库存单位
	                       MB009, --商品描述
	                       MB043, --检验方式 0:免检、1:抽检(减量)、2:抽检(正常)、3:抽检(加严)、4:全检
                           MB064, --库存数量
                           UDF07  --品牌名称
                    from INVMB where MB001='" + code + "' and MB003='" + specificationModel + "'");

            var materialErpInputModel = materialList.FirstOrDefault();

            if (materialErpInputModel != null)
            {
                //抽检方式
                var inspectionMethod = InspectionMethodEnum.mianjian;
                if (materialErpInputModel.MB043.Equals(0))
                    inspectionMethod = InspectionMethodEnum.mianjian;
                else if (materialErpInputModel.MB043.Equals(1))
                    inspectionMethod = InspectionMethodEnum.choujian_jianliang;
                else if (materialErpInputModel.MB043.Equals(2))
                    inspectionMethod = InspectionMethodEnum.choujian_zhengchang;
                else if (materialErpInputModel.MB043.Equals(3))
                    inspectionMethod = InspectionMethodEnum.choujian_jiayan;
                else
                    inspectionMethod = InspectionMethodEnum.quanjian;

                return new WareMaterial
                {
                    Code = materialErpInputModel.MB001 == null ? "" : materialErpInputModel.MB001.Trim(),
                    Name = materialErpInputModel.MB002 == null ? "" : materialErpInputModel.MB002.Trim(),
                    SpecificationModel = materialErpInputModel.MB003 == null ? "" : materialErpInputModel.MB003.Trim(),
                    Unit = materialErpInputModel.MB004 == null ? "" : materialErpInputModel.MB004.Trim(),
                    Describe = materialErpInputModel.MB009 == null ? "" : materialErpInputModel.MB009.Trim(),
                    InspectionMethod = inspectionMethod,
                    Quantity = materialErpInputModel.MB064,
                    BrandName = materialErpInputModel.UDF07,
                    SupplerCode = "",
                    IsJiaJi = YesOrNot.N,
                    CreatedUserName = "LES SYSTEM",
                    CreatedTime = DateTimeOffset.Now
                };
            }
            else
            {
                return null;
            }
        }
    }
}
